import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { isNotEmpty } from '@/utils'
import LayoutView from '../views/layout/LayoutView.vue'

const routes = [
  {
    path: '/',
    name: 'layout',
    component: LayoutView,
    redirect: '/index',
    children: [
      {
        path: '/index',
        name: '首页',
        component: () => import('@/views/home/HomeView.vue')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/user/UserView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: '/ebook',
        name: 'ebook',
        component: () => import('@/views/ebook/EbookView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: '/category',
        name: 'category',
        component: () => import('@/views/category/CategoryView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: '/doc',
        name: 'doc',
        component: () => import('@/views/doc/DocView.vue')
      },
      {
        path: 'docDetail',
        name: 'docDetail',
        component: () => import('@/views/doc/docDetailView.vue')
      },
      {
        path: 'about',
        name: 'about',
        component: () => import('@/views/about/AboutView.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
  scrollBehavior() {
    // 始终滚动到顶部
    return { top: 0 }
  }
})

router.beforeEach((from, to, next) => {
  if (from.meta.auth) {
    const userStore = useUserStore()
    const userInfo = userStore.userInfo
    if (isNotEmpty(userInfo)) {
      next()
    } else {
      next('/')
    }
  } else {
    next()
  }
})

export default router
